package com.tuo51.manager.controller;


import com.tuo51.evaluate.domain.evaluatingV2.EvaluateV2Question;
import com.tuo51.evaluate.repositories.evaluatev2.EvaluateV2QuestionRepository;
import com.tuo51.foudation.exception.BusinessException;
import com.tuo51.foudation.model.ErrorCode;
import com.tuo51.foudation.model.MemVerificationCache;
import com.tuo51.foudation.model.StatusResponse;
import com.tuo51.manager.vo.EvaluateV2QuestionVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import static com.tuo51.foudation.constant.RequestConstant.TICKET;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

@RestController
@RequestMapping("/mapi/pbe_question")
@Api(value = "/mapi/pbe_question", tags = "OP - 儿心量表内容管理 - 问题")
public class MAPIPbEvaluateQuestionController {

    @Autowired
    EvaluateV2QuestionRepository itemRepository;

    @Autowired
    MemVerificationCache cache;

    @RequestMapping(value = "/list", method = GET)
    @ApiOperation(value = "资源列表")
    public StatusResponse list(@RequestHeader(TICKET) String ticket,
                               @RequestParam(value = "pageNum", required = false, defaultValue = "0")Integer pageNum,
                               @RequestParam(value = "pageSize", required = false, defaultValue = "15")Integer pageSize,
                               @RequestParam(value = "month", required = false)Integer month,
                               @RequestParam(value = "orderBy", required = false)String orderBy,
                               @RequestParam(value = "searchBy", required = false) String searchBy){

        cache.getStaffId(ticket);

        PageRequest pageRequest = PageRequest.of(pageNum, pageSize, Sort.by("indexOnPaper"));

        Page<EvaluateV2QuestionVO> ret = itemRepository.findAll(new Specification<EvaluateV2Question>() {
            @Override
            public Predicate toPredicate(Root<EvaluateV2Question> root, CriteriaQuery<?> query, CriteriaBuilder cb) {

                Predicate base = cb.isFalse(root.get("deleted"));

                if (StringUtils.isNotEmpty(searchBy)){
                    String key = "%" + searchBy + "%";

                    Predicate p = cb.or(cb.like(root.get("title"), key),
                            cb.like(root.get("optionTitle"), key),
                            cb.like(root.get("detail"), key));

                    base = cb.and(base, p);
                }

                if (month != null){
                    Predicate p1 = cb.equal(root.get("month"), month);
                    base = cb.and(base, p1);
                }

                query.where(base);

                if (StringUtils.isNotEmpty(orderBy)){
                    query.orderBy(cb.asc(root.get(orderBy)));
                }else {
                    query.orderBy(cb.desc(root.get("indexOnPaper")));
                }

                return query.getRestriction();
            }
        }, pageRequest).map(k->EvaluateV2QuestionVO.of(k));

        return StatusResponse.success(ret);
    }

    @RequestMapping(value = "/info", method = GET)
    @ApiOperation(value = "内容详情")
    public StatusResponse info(@RequestHeader(TICKET) String ticket,
                                   String itemId){

        cache.getStaffId(ticket);

        return StatusResponse.success(itemRepository.getOne(itemId));
    }

    @RequestMapping(value = "/edit", method = POST)
    @ApiOperation(value = "编辑")
    public StatusResponse edit(@RequestHeader(TICKET) String ticket,
                               EvaluateV2QuestionVO item){

        cache.getStaffId(ticket);

        EvaluateV2Question ret = null;
        if (StringUtils.isNotEmpty(item.getId())){
            ret = itemRepository.getOne(item.getId());
        }else{
            ret = new EvaluateV2Question();
        }

        if (ret == null){
            throw new BusinessException(ErrorCode.MATERIAL_NOT_EXIST, "条目不存在");
        }

        BeanUtils.copyProperties(item, ret, new String[]{"deleted","id"});

        itemRepository.save(ret);

        return StatusResponse.success(ret);
    }
}
